<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="信息描述">
        <el-tag type="info">excel模版说明</el-tag>
        <el-tag>
          <i class="el-icon-download"/>
          <a :href="defaultExcelTemplate">点击下载模版</a>
        </el-tag>

      </el-form-item>

      <el-form-item label="选择Excel">
        <!-- 定义唯一标识，用于方法中调用$ref.upload -->
        <el-upload
          ref="upload"
          :auto-upload="false"
          :on-exceed="fileUploadExceed"
          :on-success="fileUploadSuccess"
          :on-error="fileUploadError"
          :disabled="importBtnDisabled"
          :limit="1"
          class="upload-demo"
          drag
          action="http://127.0.0.1:8110/admin/edu/subject/import"
          multiple
          name="file"
          accept="application/vnd.ms-excel"><!-- 确认文件属性 -->
          <i class="el-icon-upload"/>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">只能上传xls文件</div>
        </el-upload>
        <!-- 上传按钮 -->
        <el-button
          :loading="loading"
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload">{{ fileUploadBtnText }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default{
  data() {
    return {
      // BASE_API: process.env.BASE_API, // 接口API地址
      defaultExcelTemplate: process.env.OSS_ADDRESS + '/模板/课程分类列表模板.xls', // 阿里云OSS地址
      fileUploadBtnText: '上传到服务器', // 按钮文字
      importBtnDisabled: false, // 按钮是否禁用
      loading: false // 按钮上传中的加载状态动画
    }
  },

  methods: {
    // 防止上传多个文件
    fileUploadExceed() {
      this.$message.warning('只能选取一个文件')
    },

    submitUpload() {
      this.fileUploadBtnText = '正在上传...'
      this.importBtnDisabled = true
      this.loading = true
      this.$refs.upload.submit() // 表单提交
    },

    // 文件上传成功后的回调
    fileUploadSuccess(response) {
      if (response.success === true) {
        this.fileUploadBtnText = '导入成功'
        this.loading = false
        this.$message.success(response.message)
        this.$refs.upload.clearFiles() // 清空文件列表
      }
    },

    fileUploadError(response) {
      this.fileUploadBtnText = '导入失败'
      this.loading = false
      this.$message.error('导入失败')
    }
  }

}
</script>
